package mongodao

import (
	mongomodel "mygame/app/model/mongoModel"
	mongopkg "mygame/pkg/mongoPkg"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type Counter struct {
	ID  string `bson:"_id"`
	Seq int64  `bson:"seq"`
}

func (c Counter) db() *mongo.Collection {
	return mongopkg.DB.Collection(mongomodel.Counter{}.TableName())
}

func (c Counter) GetNextID(key string) (int64, error) {
	filter := bson.M{"_id": key}
	update := bson.M{"$inc": bson.M{"seq": 1}}
	var counter Counter
	// upsert := true
	// op := options.FindOneAndUpdateOptions{
	// 	Upsert: &upsert,
	// }
	op := options.FindOneAndUpdate().SetUpsert(true).SetReturnDocument(options.After)
	err := c.db().FindOneAndUpdate(mongopkg.Ctx, filter, update, op).Decode(&counter)
	return counter.Seq, err
}
